package com.carol.lmsbe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carol.lmsbe.dto.LoginRequest;
import com.carol.lmsbe.dto.LoginResponse;
import com.carol.lmsbe.dto.UserDTO;
import com.carol.lmsbe.entity.Laboratory;
import com.carol.lmsbe.entity.User;
import com.carol.lmsbe.mapper.LaboratoryMapper;
import com.carol.lmsbe.mapper.UserMapper;
import com.carol.lmsbe.service.UserService;
import com.carol.lmsbe.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final LaboratoryMapper laboratoryMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        // 根据用户名查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, loginRequest.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证密码
        if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 检查用户状态
        if (user.getStatus() != 1) {
            throw new RuntimeException("用户已被禁用");
        }

        // 更新最后登录时间
        user.setLastLoginTime(LocalDateTime.now());
        userMapper.updateById(user);

        // 生成JWT token
        String token = jwtUtil.generateToken(user.getUsername(), user.getId(), user.getRole());

        // 构建用户信息DTO
        UserDTO userDTO = convertToUserDTO(user);

        return new LoginResponse(token, userDTO);
    }

    @Override
    public UserDTO getCurrentUserInfo(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 如果有实验室ID，查询实验室信息
        if (user.getLaboratoryId() != null) {
            Laboratory laboratory = laboratoryMapper.selectById(user.getLaboratoryId());
            if (laboratory != null) {
                user.setRemark(laboratory.getName()); // 临时使用remark字段存储实验室名称
            }
        }

        return convertToUserDTO(user);
    }

    @Override
    public Page<UserDTO> getUserList(int page, int size, String username, String role, Long laboratoryId) {
        Page<User> userPage = new Page<>(page, size);
        
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(username), User::getUsername, username)
                   .eq(StringUtils.hasText(role), User::getRole, role)
                   .eq(laboratoryId != null, User::getLaboratoryId, laboratoryId)
                   .orderByDesc(User::getCreateTime);

        Page<User> result = userMapper.selectPage(userPage, queryWrapper);
        
        // 转换为DTO
        Page<UserDTO> dtoPage = new Page<>();
        BeanUtils.copyProperties(result, dtoPage, "records");
        
        List<UserDTO> userDTOs = result.getRecords().stream()
                .map(this::convertToUserDTO)
                .collect(Collectors.toList());
        
        dtoPage.setRecords(userDTOs);
        return dtoPage;
    }

    @Override
    @Transactional
    public UserDTO createUser(UserDTO userDTO) {
        // 检查用户名是否已存在
        User existingUser = userMapper.selectByUsernameWithLaboratory(userDTO.getUsername());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建用户实体
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        
        // 加密密码
        if (StringUtils.hasText(userDTO.getPassword())) {
            user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        } else {
            user.setPassword(passwordEncoder.encode("123456")); // 默认密码
        }
        
        // 设置默认状态
        if (user.getStatus() == null) {
            user.setStatus(1);
        }

        userMapper.insert(user);
        
        return convertToUserDTO(user);
    }

    @Override
    @Transactional
    public UserDTO updateUser(Long id, UserDTO userDTO) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 更新用户信息
        BeanUtils.copyProperties(userDTO, user, "id", "password", "createTime");
        
        // 如果提供了新密码，则加密更新
        if (StringUtils.hasText(userDTO.getPassword())) {
            user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        }

        userMapper.updateById(user);
        
        return convertToUserDTO(user);
    }

    @Override
    @Transactional
    public void deleteUser(Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        userMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void resetPassword(Long id, String newPassword) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        user.setPassword(passwordEncoder.encode(newPassword));
        userMapper.updateById(user);
    }

    @Override
    public User getUserByUsername(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public List<Laboratory> getAllActiveLaboratories() {
        return laboratoryMapper.selectAllActive();
    }

    /**
     * 转换为UserDTO
     */
    private UserDTO convertToUserDTO(User user) {
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        
        // 设置实验室名称
        if (user.getLaboratoryId() != null) {
            Laboratory laboratory = laboratoryMapper.selectById(user.getLaboratoryId());
            if (laboratory != null) {
                userDTO.setLaboratoryName(laboratory.getName());
            }
        }
        
        return userDTO;
    }
}
